import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    houseInfo: '',
    houseId: '',
    name: '',
    gender: '',
    mobile: '',
    visitDate: '',
    currentDate: new Date().getTime(),
  },
  rules: {
    houseInfo: [{ required: true, message: '请填写房屋信息！' }],
    name: [{ required: true, message: '请填写姓名!' }],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      {
        pattern: /^1[3456789]\d{9}$/,
        message: '请检查手机号码是否正确!',
      },
    ],
    visitDate: [{ required: true, message: '请请选择访问日期!' }],
    gender: [{ required: true, message: '请选择性别！' }],
  },
  async onShow() {
    const { data } = await wx.http.get('/house')
    console.log(data)
    this.setData({
      houseList: data,
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer(e) {
    console.log(e)
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    console.log('3232')
    this.setData({ dateLayerVisible: true })
  },
  getCurrentData(e) {
    const date = new Date(e.detail)
    const year = date.getFullYear()
    const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    this.setData({
      visitDate: `${year}-${month}-${day}`,
      dateLayerVisible: false,
    })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  selectHouseLayer(e) {
    this.setData({
      houseLayerVisible: false,
      houseInfo: e.detail.name,
      houseId: e.detail.id,
    })
  },
  async goPassport() {
    this.validate()
    const data = {
      houseId: this.data.houseId,
      name: this.data.name,
      gender: this.data.gender - '1',
      mobile: this.data.mobile,
      visitDate: this.data.visitDate,
    }
    const {
      data: { id },
    } = await wx.http.post('/visitor', data)
    console.log(id)
    wx.reLaunch({
      url: `/visitor_pkg/pages/passport/index?id=${id}`,
    })
  },
})
